package com.ruoyi.SSL.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.SSL.domain.SslDomain;
import com.ruoyi.SSL.mapper.SslDomainMapper;
import com.ruoyi.SSL.service.ISslApplyService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.SSL.mapper.SslTrusteeshipServiceMapper;
import com.ruoyi.SSL.domain.SslTrusteeshipService;
import com.ruoyi.SSL.service.ISslTrusteeshipServiceService;
import com.ruoyi.common.core.text.Convert;

import javax.servlet.http.HttpServletRequest;

/**
 * 托管服务器Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-27
 */
@Service
public class SslTrusteeshipServiceServiceImpl implements ISslTrusteeshipServiceService
{
    @Autowired
    private SslTrusteeshipServiceMapper sslTrusteeshipServiceMapper;

    @Autowired
    private SslDomainMapper domainMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISslApplyService applyService;


    /**
     * 查询托管服务器
     *
     * @param id 托管服务器主键
     * @return 托管服务器
     */
    @Override
    public SslTrusteeshipService selectSslTrusteeshipServiceById(Long id)
    {
        return sslTrusteeshipServiceMapper.selectSslTrusteeshipServiceById(id);
    }

    /**
     * 查询托管服务器列表
     *
     * @param sslTrusteeshipService 托管服务器
     * @return 托管服务器
     */
    @Override
    public List<SslTrusteeshipService> selectSslTrusteeshipServiceList(SslTrusteeshipService sslTrusteeshipService)
    {
        return sslTrusteeshipServiceMapper.selectSslTrusteeshipServiceList(sslTrusteeshipService);
    }

    /**
     * 新增托管服务器
     *
     * @param sslTrusteeshipService 托管服务器
     * @return 结果
     */
    @Override
    public int insertSslTrusteeshipService(SslTrusteeshipService sslTrusteeshipService)
    {
        sslTrusteeshipService.setCode(RandomUtil.randomString(8));
        sslTrusteeshipService.setCreateTime(DateUtils.getNowDate());
        sslTrusteeshipService.setLastCheckDate(DateUtils.getNowDate());
        return sslTrusteeshipServiceMapper.insertSslTrusteeshipService(sslTrusteeshipService);
    }

    /**
     * 修改托管服务器
     *
     * @param sslTrusteeshipService 托管服务器
     * @return 结果
     */
    @Override
    public int updateSslTrusteeshipService(SslTrusteeshipService sslTrusteeshipService)
    {
        if(StringUtils.isBlank(sslTrusteeshipService.getCode())){
            sslTrusteeshipService.setCode(RandomUtil.randomString(8));
        }
        sslTrusteeshipService.setUpdateTime(DateUtils.getNowDate());
        return sslTrusteeshipServiceMapper.updateSslTrusteeshipService(sslTrusteeshipService);
    }

    /**
     * 批量删除托管服务器
     *
     * @param ids 需要删除的托管服务器主键
     * @return 结果
     */
    @Override
    public int deleteSslTrusteeshipServiceByIds(String ids)
    {
        return sslTrusteeshipServiceMapper.deleteSslTrusteeshipServiceByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除托管服务器信息
     *
     * @param id 托管服务器主键
     * @return 结果
     */
    @Override
    public int deleteSslTrusteeshipServiceById(Long id)
    {
        return sslTrusteeshipServiceMapper.deleteSslTrusteeshipServiceById(id);
    }

    public List<Ztree> selectTree(SslTrusteeshipService trusteeshipService){
        List<SslTrusteeshipService> dataList = sslTrusteeshipServiceMapper.selectSslTrusteeshipServiceList(trusteeshipService);
        for (SslTrusteeshipService sslTrusteeshipService : dataList) {
            SslDomain domain = new SslDomain();
            domain.setStsId(sslTrusteeshipService.getId().toString());
            List<SslDomain> domainList = domainMapper.selectSslDomainList(domain);
            sslTrusteeshipService.setDomainList(domainList);
        }
        return initZtree(dataList);
    }

    /**
     * 对象转部门树
     *
     * @param trusteeshipServiceList 服务器列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SslTrusteeshipService> trusteeshipServiceList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (SslTrusteeshipService trusteeshipService : trusteeshipServiceList)
        {
            if (UserConstants.DEPT_NORMAL.equals(trusteeshipService.getStatus()))
            {
                Ztree ztree = new Ztree();
                ztree.setId(trusteeshipService.getId());
                ztree.setpId(0L);
                ztree.setName(trusteeshipService.getSerName());
                ztree.setTitle(trusteeshipService.getSerName());
                ztrees.add(ztree);
                for (SslDomain sslDomain : trusteeshipService.getDomainList()) {
                    ztree = new Ztree();
                    ztree.setId(sslDomain.getId());
                    ztree.setpId(trusteeshipService.getId());
                    ztree.setName(sslDomain.getCertificateDomain());
                    ztree.setTitle(sslDomain.getCertificateDomain());
                    ztrees.add(ztree);
                }
            }
        }
        return ztrees;
    }


    public String getRunAutoScript(){
        StringBuilder runAutoScript = new StringBuilder();
        runAutoScript.append("curl -s ");
        try {
            HttpRequest request = HttpRequest.post(CommUtils.REQ_API_URI+"/SSL/api/v1/getSerFile");
            //先封装参数得到签名值
            JSONObject paramObj = new JSONObject();
            //先封装参数得到签名值
            paramObj.set("appId", configService.selectConfigByKey("api.appId"));
            paramObj.set("fileType", "1");
            //得到签名
            String sign = SignUtils.createSign(paramObj, configService.selectConfigByKey("api.appSecret"));
            //赋值必要请求头的值
            request.header("Referer", configService.selectConfigByKey("self.domain"));
            request.header("ssl-sign", sign);   //签名字符串
            request.header("ssl-appid", configService.selectConfigByKey("api.appId"));  //appid
            request.header("ssl-timestamp", String.valueOf(DateUtil.current()));    // 当前时间戳
            //把请求参数赋值到请求中
            request.body(JSONUtil.toJsonStr(paramObj));
            //发起请求
            HttpResponse response = request.execute();
            if(response.getStatus() == 200){
                JSONObject resObj = JSONUtil.parseObj(response.body());
                if(resObj.getInt("code") == 0){
                    JSONObject dataObj = JSONUtil.parseObj(resObj.getStr("data"));
                    //把文件下载下来到本地
                    String fileUrl = CommUtils.REQ_API_URI+dataObj.getStr("filePath").trim();
                    String fielName = dataObj.getStr("filePath").substring(dataObj.getStr("filePath").lastIndexOf("/"));
                    //下载文件到本地
                    FileUtils.downHttpsFile(fileUrl, RuoYiConfig.getUploadPath()+fielName);
                    //拼接字符串
                    runAutoScript.append(configService.selectConfigByKey("self.domain")+"/profile/upload"+fielName);
                }else{
                    return null;
                }
            }
            //获取到平台
            runAutoScript.append(" | bash -s "+configService.selectConfigByKey("script.token") +" "+configService.selectConfigByKey("self.domain")
                    .replace("https://","").replace("http://", ""));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return runAutoScript.toString();
    }

    /**
     * 通过请求投获取到IP然后判断是否存在该服务器  如果不存在则添加新的服务器信息
     * @param req 请求投
     * @return 返回服务器对象
     */
    public SslTrusteeshipService getSerInfoByReq(HttpServletRequest req){
        //得到IP
        String reqIP = CommUtils.getClientIp(req);
        //通过IP查询服务器
        SslTrusteeshipService sslTrusteeshipService = new SslTrusteeshipService();
        sslTrusteeshipService.setSerIp(reqIP);
        //查询数据
        List<SslTrusteeshipService> serviceList = selectSslTrusteeshipServiceList(sslTrusteeshipService);
        //判断是否存在服务器信息
        if(serviceList != null && serviceList.size()> 0){
            sslTrusteeshipService = serviceList.get(0);
            //更新最后连接系统时间
            sslTrusteeshipService.setLastCheckDate(DateUtil.date());
            //更新数据
            updateSslTrusteeshipService(sslTrusteeshipService);
        }else{
            insertSslTrusteeshipService(sslTrusteeshipService);
        }
        return sslTrusteeshipService;
    }
}
